<?php

namespace Home\Controller;

class DatumController extends HomeCoreController {
	
	public $Model = null;

    protected function _initialize(){
		
        parent::_initialize();
		
        $this->Model = D('Datum');
		
    }
	
	public function index(){
		
		if(IS_AJAX){
						
			$mark = I('get.mark');
			
			if(!empty($mark)){
				$map['type'] = array('like', "$mark");
			}
			
			$search = I('get.search');
			
			if(!empty($search)){
				$map['title'] = array('like', "%$search%");
			}
			
			$map['uid'] = session(C('AUTH_KEYS'));
			
			$page_size = 10;
			
			$count = $this->Model->where($map)->count();
			
			$Page = new \Think\Page($count, $page_size);
			
			$list = $this->Model
				->where($map)
				->order("id desc")
				->limit($Page->firstRow . ',' . $Page->listRows)
				->select();
				
			foreach($list as $k=>$v){
				
				$list[$k]['files'] = str_replace('./', __ROOT__.'/', $list[$k]['files']);
				
				$list[$k]['opt'] = '<a href="'.$list[$k]['files'].'" target="_blank">查看</a>&nbsp;&nbsp;<a href="'.U('Home/Datum/filedown',array('id'=>$list[$k]['id'])).'">下载</a>';
				
			}
			
			$str = $this->tojson($list, $count);
			
			echo $str;
			
			exit;
			
        }else{
			
			$list = M('Filetype')->where($map)->order('id asc')->select();
			
			$this->assign("filetype", $list);
			
            $this->display();
			
        }
		
    }
	
	public function filedown(){
		
		$_info=I('get.');
		
		$info = $this->Model->where(array('id'=>$_info['id']))->find();
		
		$data = str_replace('./', '/', $info['files']);
			
		$b = explode(".", $data);
			
		$d['url'] = $b[0];
			
		$d['ext'] = $b[1];
			
		$ext = ".".$d['ext'];

    	$file_dir = $info['files'];
		
		if (!file_exists($file_dir)){
			
        	exit('文件不存在');
			
		}else{
			
			$file = fopen($file_dir, "r");
			
			$filename = $info['title'];
			
			header('Content-Encoding: none');
			
			header("Content-type: application/octet-stream");
			
			header("Accept-Ranges: bytes");
			
			header("Accept-Length: " . filesize($file_dir));
			
			header('Content-Transfer-Encoding: binary');
			
			header("Content-Disposition: attachment; filename=" . $filename . $ext);
			
			header('Pragma: no-cache');
			
			header('Expires: 0');
			
			echo fread($file, filesize($file_dir));
			
			fclose($file);
			
			exit;
			
		}
		
	}
	
	public function add(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$data = $this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->update($data);
				
				if($result){
					
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
				}else{
					
					$error = $this->Model->getError();
					
					echo json_encode(array('info'=>$error, 'status'=>'n'));
					
				}
				
			}else{
				
				$error = $this->Model->getError();
				
				echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}	
					
		}else{
			
			$map['uid'] = session('gid');
			
			$list = M('Filetype')->where($map)->order('id asc')->select();
			
			$this->assign("filetype", $list);
			
			$this->display();
			
		}
		
	}
	
	public function edit(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$data=$this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->where(array('id'=>$post_data['id']))->update($data);
				
				if($result){
					
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
				}else{
					
					$error = $this->Model->getError();
					
					echo json_encode(array('info'=>$error, 'status'=>'n'));
					
				}
				
			}else{
				
                $error = $this->Model->getError();
				
                echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}
			
		}else{

			$info=I('get.');
			
			$info = $this->Model->where(array('id'=>$info['id']))->find();
						
			if(!empty($department)){
				
				$map['title'] = array('not in', $department);
				
			}
			
			$map['uid'] = session('gid');
			
			$map['title'] = array('not in', $info['type']);
			
			$list = M('Filetype')->where($map)->order('id asc')->select();
			
			$this->assign("filetype", $list);
			
			$this->assign('info', $info);
						
        	$this->display();
			
		}
		
	}
	
	public function del(){
		
		$ids = I('get.ids');
		
        $map['id'] = array('in', $ids);
		
        $res = $this->Model->where($map)->delete();
		
        if($res){
			
            echo json_encode(array('info'=>'删除成功', 'status'=>'y'));
			
        }else{
			
            $error = $this->Model->getError();
			
			echo json_encode(array('info'=>$error, 'status'=>'n'));
			
        }
		
	}
	
	public function uploadify(){
		
		$type = I('post.type');
		
		$targetPath = './Public/datum/';
		
		if(!file_exists($targetPath)){
				
			mkdir($targetPath);
				
		}
		
        $config = array(
            'maxSize' => 52428800,
            'rootPath' => './',
            'savePath' => $targetPath,
            'saveName' => array('uniqid', ''),
            'exts' => array('pdf'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
			'saveName' => array('date', 'YmdHis'),
        );
		
		$verifyToken = md5($_POST['timestamp']);

		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
		
			$upload = new \Think\Upload($config);
			
			$info = $upload->upload();
			
			if(!$info){
				
				$arr = array(
					'status' => 0,
					'type' => $type,
					'msg' => $upload->getError()
				);
				
			}else{
				
				$ajaxname = $info['Filedata']['savepath'] . $info['Filedata']['savename'];
				
				$arr = array(
					'status' => 1,
					'type' => $type,
					'name' => $info['Filedata']['name'],
					'url' => $ajaxname
				);
				
			}
			
			echo json_encode($arr);
			
			exit;
		
		}
		
    }
	
	public function dels(){
		
		$url = I('post.name');
		
		if($url != ""){
			
    		if(unlink($url)){
				
    			$this->success("删除成功");
				
    		}else{

    			$this->error($url);
				
			}
				
    	}else{
			
    		$this->error("删除失败");
			
		}
		
	}
	
}